package com.bsi.core.converter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.convert.converter.Converter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/*
 * Author: liusongs
 * Date: 2019/10/24 17:13
 * Content: 时间转化器，解决前端传过来的时间无法匹配的问题
 */

public class DateConverterEx implements Converter<String, Date> {

    private Logger logger = LoggerFactory.getLogger(DateConverterEx.class);

    private final List<String> datePattren = new ArrayList<String>() {
        {
            // 可自定义增加规则属性
            add("yyyy-MM-dd hh:mm:ss");
            add("yyyy-MM-dd");
            add("yyyy/MM/dd hh:mm:ss");
            add("yyyy/MM/dd");
        }
    };


    @Override
    public Date convert(String s) {
        return getDateFormat(s);
    }

    private Date getDateFormat(String s) {
        SimpleDateFormat simpleDateFormat = null;
        Date parse = null;
        for (String pattern : datePattren) {
            try {
                simpleDateFormat = new SimpleDateFormat(pattern); // 不报错说明解析成功
                parse = simpleDateFormat.parse(s);
            } catch (Exception e) {

            }
        }
        return parse;
    }
}
